from django.db import models
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User
from apps.instruments.models import InstrumentType, Instrument

class DataType(models.Model):

    name = models.CharField(max_length=40)
    alias = models.CharField(max_length=40)
    itype = models.ForeignKey(InstrumentType)
    filename = models.CharField(max_length=40)
    info = models.TextField(blank=True, null=True)
    STATES = (
         (0, 'Inactive'),
         (1, 'Active'),
    )
    status = models.PositiveSmallIntegerField(default=1, choices=STATES)

    class Meta:
        db_table = "data_types"
        verbose_name = "Data Type"
        verbose_name_plural = "Data Types"
    
    def __unicode__(self):
        return u'%s' % self.alias

class Data(models.Model):

    instrument = models.ForeignKey(Instrument)
    datatype = models.ForeignKey(DataType)
    path = models.CharField(max_length=128)
    info = models.TextField(blank=True, null=True)
    STATES = (
         (0, 'Inactive'),
         (1, 'Active'),                                   
    )
    status = models.PositiveSmallIntegerField(default=1, choices=STATES)

    class Meta:
        db_table = "data"
        verbose_name = "Data"
    
    def __unicode__(self):
        return u'%s-%s' % (self.instrument, self.datatype)
        
class DataDate(models.Model):

    data = models.ForeignKey(Data)
    date = models.DateField()
    numfiles = models.PositiveIntegerField(default=0)
    size = models.PositiveIntegerField(default=0)   
    STATES = (
         (0, 'Inactive'),
         (1, 'Active'),                                   
    )
    status = models.PositiveSmallIntegerField(default=1, choices=STATES)

    class Meta:
        db_table = "data_dates"
        verbose_name = "Data Date"
        verbose_name_plural = "Data Dates"
    
    def __unicode__(self):
        return u'%s' % self.date

class DataDownload(models.Model):

    user = models.ForeignKey(User)
    session = models.ForeignKey(Session)
    code = models.CharField(max_length=40)
    numfiles = models.PositiveIntegerField(default=0)
    size = models.PositiveIntegerField(default=0)   
    info = models.TextField(blank=True, null=True)
    STATES = (
         (0, 'Registered'),
         (1, 'Ready'),
         (2, 'Running'),
         (3, 'Finished'),
    )
    status = models.PositiveSmallIntegerField(default=0, choices=STATES)

    class Meta:
        db_table = "data_download"
        verbose_name = "Data Download"
        verbose_name_plural = "Data Downloads"
    
    def __unicode__(self):
        return u'%s' % self.user.username

    def get_state(self):
    
        return [tup for tup in self.STATES if self.status==tup[0]][1]
